package com.wwdeng.print.app.meituan;

import android.graphics.Bitmap;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * PrintTestDemo
 *
 * @Author：wwdeng
 * @CreateTime：2025/5/20 00:12
 * <pre>
 *  获取打印图片的十进制指令
 * </pre>
 */
public class MeiTuanEscPosImageUtils {

    // 标准打印纸宽度（点单位  80mm为576）
    private static final int PAPER_WIDTH = 576;
    private static final int TARGET_WIDTH = PAPER_WIDTH / 2; // 打印纸一半宽度

    /**
     * 获取图片打印指令
     * @param bitmap 原始Bitmap图片
     * @return ESC/POS十进制指令byte[]
     */
    public static byte[] getImagePrintCommand(Bitmap bitmap) {
        try {
            // 1. 调整图片大小为打印纸一半宽度（保持宽高比）
            Bitmap resizedBitmap = resizeBitmap(bitmap, TARGET_WIDTH);

            // 2. 二值化处理（自动阈值）
            Bitmap bwBitmap = convertToBlackAndWhite(resizedBitmap);
            resizedBitmap.recycle();

            // 3. 生成ESC/POS指令
            return generateEscPosCommands(bwBitmap);

        } catch (Exception e) {
            e.printStackTrace();
            return new byte[0];
        }
    }

    /**
     * 调整Bitmap大小（保持宽高比）
     */
    private static Bitmap resizeBitmap(Bitmap original, int targetWidth) {
        float ratio = (float) targetWidth / original.getWidth();
        int targetHeight = (int) (original.getHeight() * ratio);
        return Bitmap.createScaledBitmap(original, targetWidth, targetHeight, true);
    }

    /**
     * 图片二值化处理（自动计算阈值）
     */
    private static Bitmap convertToBlackAndWhite(Bitmap original) {
        int width = original.getWidth();
        int height = original.getHeight();
        Bitmap bwBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);

        // 自动计算阈值（Otsu算法）
        int threshold = calculateOtsuThreshold(original);

        // 应用阈值
        int[] pixels = new int[width * height];
        original.getPixels(pixels, 0, width, 0, 0, width, height);

        for (int i = 0; i < pixels.length; i++) {
            int color = pixels[i];
            int r = (color >> 16) & 0xff;
            int g = (color >> 8) & 0xff;
            int b = color & 0xff;
            int gray = (r + g + b) / 3;
            pixels[i] = (gray < threshold) ? 0xFF000000 : 0xFFFFFFFF;
        }

        bwBitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        return bwBitmap;
    }

    /**
     * Otsu自动阈值算法
     */
    private static int calculateOtsuThreshold(Bitmap bitmap) {
        // 实现Otsu阈值计算...
        // 值越小打印越黑
        return 128;
    }

    /**
     * 生成ESC/POS十进制指令
     */
    private static byte[] generateEscPosCommands(Bitmap bitmap) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int bytesPerLine = (int) Math.ceil(width / 8.0);

        // 2. 设置行间距 (ESC 3 n)
        output.write(new byte[]{27, 51, 24}); // 24点间距

        // 3. 位图模式 (GS v 0)
        output.write(new byte[]{29, 118, 48, 0});

        // 4. 宽度和高度（低位在前）
        output.write(bytesPerLine % 256);   // xL
        output.write(bytesPerLine / 256);   // xH
        output.write(height % 256);        // yL
        output.write(height / 256);        // yH

        // 5. 生成位图数据
        for (int y = 0; y < height; y++) {
            byte[] line = new byte[bytesPerLine];
            for (int x = 0; x < width; x++) {
                if (bitmap.getPixel(x, y) != 0xFFFFFFFF) { // 非白色像素
                    int bytePos = x / 8;
                    int bitPos = 7 - (x % 8);
                    line[bytePos] |= (1 << bitPos);
                }
            }
            output.write(line);
        }

        // 6. 恢复默认设置
        output.write(new byte[]{27, 50}); // ESC 2 (恢复默认行距)

        return output.toByteArray();
    }
}
